import { createRouter, createWebHashHistory } from 'vue-router'

// 静态加载、立马加载
// import Login from '@/views/Login'
// import Layout from '@/views/Layout'
// import Home from '@/views/Home'
// import Category from '@/views/Category'
// import Cart from '@/views/Cart'
// import My from '@/views/My'
// import GoodsDetail from '@/views/GoodsDetail'
// import Order from '@/views/Order'
// import GoodsList from '@/views/GoodsList'

import { useUserStore } from '@/store/modules/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })

// 动态加载（路由懒加载）
const Login = () => import('@/views/Login/index.vue')
const Layout = () => import('@/views/Layout/index.vue')
const Home = () => import('@/views/Home/index.vue')
const Category = () => import('@/views/Category/index.vue')
const Cart = () => import('@/views/Cart/index.vue')
const My = () => import('@/views/My/index.vue')
const GoodsDetail = () => import('@/views/GoodsDetail/index.vue')

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录'
    }
    // beforeEnter: (to, from, next) => {
    //   // ...
    //   next()
    // }
  },
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    redirect: '/home',
    meta: {
      title: '布局'
    },
    children: [
      {
        path: 'home',
        name: 'home',
        component: Home,
        meta: {
          title: '首页'
        }
      },
      {
        path: 'category',
        name: 'category',
        component: Category,
        meta: {
          title: '分类'
        }
      },
      {
        path: 'cart',
        name: 'cart',
        component: Cart,
        meta: {
          title: '购物车'
        }
      },
      {
        path: 'my',
        name: 'my',
        component: My,
        meta: {
          title: '我的',
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: '/detail',
    component: GoodsDetail,
    meta: {
      title: '商品详情'
    }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

/**
 * to 去哪里去
 * from 你从何而来
 * next 让你能往下继续
 */
const rightRoute = ['/my']
/**
 * 进入到某个页面之前
 */
router.beforeEach(to => {
  NProgress.start()
  const userStore = useUserStore()
  if (rightRoute.includes(to.path)) {
    if (to.meta.requiresAuth) {
      // 进而判断，你是否登录了
      const token = userStore.getToken()
      if (token) {
        // 登录了，直接放行
        return true
      } else {
        // 跳转到登录页面
        return '/login'
      }
    } else {
      // 直接放行
      return true
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
  // 设置标题
  document.title = to.meta.title
})

export default router
